/**
 * Copyright 厦门中软海晟信息技术有限公司 版权所有 违者必究 2019
 */
package com.leetCode;

/**
 * @author : sunzb(sunzb@hsit.com.cn)
 * @date: 2019/5/13
 */
public class _11_50_Pow {

    public double myPow2(double x, int n) {
        long N = n;
        if (N < 0) {
            N = -N;
            x = 1 / x;
        }
        double ans = 1;
        double prod = x;
        for (; N > 0; N /= 2) {
            if (N % 2 == 1)
                ans *= prod;
            prod *= prod;
        }
        return ans;
    }

    public double myPow3(double x, int n) {
        long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        double pow = 1;
        while (N > 0) {
            if ((N & 1) == 1) {
                pow *= x;
            }
            x *= x;
            N >>= 1;
        }
        return pow;
    }

    public double myPow1(double x, int n) {
        boolean isMinInteger = false;
        if (n < 0) {
            x = 1 / x;
            if (n == Integer.MIN_VALUE) {
                n = -(n + 1);
                isMinInteger = true;
            } else {
                n = -n;
            }
        }
        double newX = x;
        double pow = 1;
        while (n > 0) {
            if ((n & 1) == 1) {
                pow *= newX;
            }
            newX *= newX;
            n >>= 1;
        }
        if (isMinInteger) {
            return pow * x;
        }
        return pow;
    }

    public static double myPow(double x, int n) {
        return Math.pow(x, n);
    }

    public static void main(String[] args) {
        System.out.println(myPow(2.00000, -2147483648));
        System.out.println(new _11_50_Pow().myPow1(4.00000, -2));
        System.out.println(new _11_50_Pow().myPow1(2.00000, -2147483648));
        System.out.println(new _11_50_Pow().myPow2(2.00000, -2147483648));
        System.out.println(new _11_50_Pow().myPow3(2.00000, -2147483648));
    }
}
